//
//  String+JSON.swift
//  iPhoneUTests
//
//  Created by Toj on 1/26/24.
//

import XCTest

final class String_JSON: XCTestCase {

    override func setUpWithError() throws {
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDownWithError() throws {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
    }

    func testExample() throws {
        testStringToJSON()
    }

    func testPerformanceExample() throws {
        // This is an example of a performance test case.
        self.measure {
            // Put the code you want to measure the time of here.
        }
    }
}

extension String_JSON {
    
    func testStringToJSON() {
        let array = [0, 1, 2, 3, 4]
        let value: Encodable = 1
        if let dd = "1".data(using: .utf8) {
            print("-->UTests: catch: dd:\(dd)")
        }
       
        if let dd2 = value.cm_data {
            print("-->UTests: catch: dd2:\(dd2)")
        }
        
        if let dd3 = try? JSONSerialization.data(withJSONObject: value, options: .fragmentsAllowed) {
            print("-->UTests: catch: dd3:\(dd3)")
        }
        
        //httpBody = try encoder.encode(encodable)
        do {
            let encoder = JSONEncoder()
            let s = try encoder.encode("1")
            print("-->UTests: catch: encode")
        } catch  {
            print("-->UTests: catch msg:\(error.localizedDescription)")
        }
        var jsonString = ""
        
        jsonString = "\(array)"
        print("-->UTests: jsonString0: \(jsonString)")

//        jsonString = array.toJSONString() ?? ""
//        print("-->UTests: jsonString1: \(jsonString)")
//
//        jsonString = array.toJSONString(prettyPrint: true) ?? ""
//        print("-->UTests: jsonString2: \(jsonString)")
        
        if let data = try? JSONSerialization.data(withJSONObject: array, options: .fragmentsAllowed) {
            jsonString = String(data: data, encoding:.utf8) ?? ""
            print("-->UTests: jsonString3: \(jsonString)")
        }
        
        jsonString = [0, 1, 2, 3, 4].to_json ?? ""
        print("-->UTests: jsonString4: \(jsonString)")
    }
}
